package com.aash.persistence.generic;

import java.io.Serializable;
import java.util.List;

import javax.persistence.EntityManager;

public class GenericDaoJpaImpl<T, PK extends Serializable> implements GenericDao<T,PK> {

	private Class<T> type;

	private EntityManager em;
	
	public GenericDaoJpaImpl(Class<T> type) {
        this.type = type;
  }
	
	@Override
	public T create(T newInstance) {
		createEm();
		try {
		em.persist(newInstance);
		return newInstance;
		} finally {
			closeEm();
		}
	}

	@Override
	public T find(PK id) {
		return em.find(type, id);
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<T> findAll() {
		return (List<T>) em.createQuery("select p from " + type.getSimpleName() + " p").getResultList();
	}

	@Override
	public T update(final T transientObject) {
		T persistentObject;
		em.getTransaction().begin();
		persistentObject =  em.merge(transientObject);
		em.getTransaction().commit();
		return persistentObject;
	}

	/**
	 * Parameter Object may be transient or not, a merge is made systematically.
	 */
	@Override
	public void delete(final T object) {
		em.getTransaction().begin();
		T persistentObject = em.merge(object);
		em.remove(persistentObject);
		em.getTransaction().commit();
	}

	protected void createEm() {
		em = EMF.get().createEntityManager();
	}
	
	protected void closeEm() {
		if(em != null && em.isOpen()) {
			em.close();
		}
	}
	
	/**
	 * @return the em
	 */
	protected final EntityManager getEm() {
		return em;
	}

}
